﻿using DevFramework.IDal;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;

namespace DevFramework.Bll
{
    public  class BaseService<TEntity> where TEntity : class, new()
    {

       

        public IBaseDal<TEntity> currentDal { get; set; }




        public IQueryable<TEntity> All()
        {
            return currentDal.All();
        }

        //public TEntity Single(long id)
        //{
        //    return All().Single(t => t.Id == id);
        //}

        //public TEntity Single(long id, params Expression<Func<TEntity, object>>[] propertySelectors)
        //{
        //    return Find(s => s.Id == id, propertySelectors).FirstOrDefault();
        //}

        public TEntity Single(Expression<Func<TEntity, bool>> predicate)
        {
            return currentDal.Single(predicate);
        }

        public IQueryable<TEntity> Find(Expression<Func<TEntity, bool>> predicate)
        {
            return currentDal.Find(predicate);
        }

        /// <summary>
        /// 取过滤数据，启用延迟查询
        /// </summary>
        /// <param name="predicate">过滤条件</param>
        /// <param name="propertySelectors">需要Left Join 的表</param>
        /// <returns></returns>
        //public IQueryable<TEntity> Find(Expression<Func<TEntity, bool>> predicate, params Expression<Func<TEntity, object>>[] propertySelectors)
        //{
        //    if (propertySelectors.IsNullOrEmpty())
        //    {
        //        return Find(predicate);
        //    }

        //    var query = Find(predicate);

        //    foreach (var propertySelector in propertySelectors)
        //    {
        //        query = query.Include(propertySelector);
        //    }

        //    return query;
        //}

        public int Count()
        {
            return All().Count();
        }

        public int Count(Expression<Func<TEntity, bool>> criteria)
        {
            return currentDal.Count(criteria);
        }

        public IEnumerable<TEntity> Get<TOrderBy>(Expression<Func<TEntity, bool>> criteria, Expression<Func<TEntity, TOrderBy>> orderBy, int pageIndex, int pageSize, SortOrder sortOrder = SortOrder.Ascending)
        {
            return currentDal.Get(criteria, orderBy, pageIndex, pageSize, sortOrder);
        }

        //public TEntity Delete(long id)
        //{
        //    var entity = Single(id);
        //    context.Set<TEntity>().Remove(entity);
        //    context.SaveChanges();
        //    return entity;
        //}

        public bool Add(TEntity entity)
        {
            return currentDal.Add(entity);
        }

        public bool Update(TEntity entity)
        {
            return currentDal.Update(entity);
        }

        public int Save(TEntity entity)
        {
            return currentDal.Save(entity);
        }
    }
}
